import { reqShopCart, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

const state = {
  cartInfoList: []
}
const mutations = {
  setCartInfoList(state, cartInfoList) {
    state.cartInfoList = cartInfoList
  }
}
const actions = {
  // 获取购物车列表
  async getCartInfoList({ commit }) {
    const result = await reqShopCart()
    if (result.code == 200) {
      commit('setCartInfoList', result.data[0].cartInfoList || [])
    }
  },
  // 删除购物车的某一个产品
  async deleteCartListBySkuId({ commit }, skuId) {
    const result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改购物车某一个产品的选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    const result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除购物车全部选中的产品
  deleteAllCheckedCart({ getters, dispatch }) {
    let promiseAll = []
    getters.cartInfoList.forEach((item) => {
      let promise =
        item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : ''
      promiseAll.push(promise)
    })
    // 返回全部的删除结果：如果都成功，返回结果即成功，
    // 只要有一个不成功，返回结果即不成功
    return Promise.all(promiseAll)
  },
  // 全选的勾选与不勾选
  updateAllCartIsChecked({ dispatch, state }, isChecked) {
    let promiseAll = []
    state.cartInfoList.forEach((item) => {
      let promise = dispatch('updateCheckedById', {
        skuId: item.skuId,
        isChecked
      })
      promiseAll.push(promise)
    })
    // 最终返回的结果
    return Promise.all(promiseAll)
  }
}
const getters = {
  cartInfoList(state) {
    return state.cartInfoList || []
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
